import { Component } from 'react';
import React from 'react';
import { connect } from 'umi';
import {
    Button,
    DatePicker,
    Form,
    Input,
    Select,
    Space,
    Switch,
    Table,
    Modal,
    Collapse,
    message,
    Upload,
    Popconfirm,
} from 'antd';
import SearchAbleSelect from '@/components/SearchAbleSelect';
import APIS from '@/apis';
import { FormInstance } from 'antd/lib/form';
import TextArea from 'antd/lib/input/TextArea';
import ImageUpload from '@/components/ImageUpload';
import moment from 'moment';
import VideoUpload from '@/components/VideoUpload';
import VideoUploadExamine from '@/components/VideoUploadExamine';
import { number, string } from 'prop-types';
import locale from 'antd/es/date-picker/locale/zh_CN';
import HighPerformTable from '@/components/HighPerformTable';
import CourseMemberEditor from './CourseMemberEditor';
import VideoUploadAndSelect from '../../../components/VideoUploadAndSelect/index';
import URLS from '@/apis/APIUrlDefine';
import TagsManager from '../test/TagsManager';
/* 课程审核页 */
export default class CourseExamine extends Component<any, any> {
    formInstance?: FormInstance | null;

    constructor(props: any) {
        super(props);
        this.state = {
            editorData: null,
            courseTag: [],
            courseType: -1,
            courseMode: -1,
            videoUrl: null,
            imageUrl: null,
            startTime: null,
            endTime: null,
            courseTeachers: [],
            willAddTeacher: { id: -1 },

            courseChapters: [],
            courseChaptersList: [],
            chapterVisible: false,
            chapterEditorData: { id: null, chapterName: null, lessonType: null, parent: null },

            chapterCourseIndex: 0,
            chapterCourseVisible: false,
            courseId: -1,
            chapterCourseData: {
                id: number,
                chapterId: number,
                description: string,
                lessonName: string,
                lessonIndex: number,
                articleId: number, //文章课程
                lessonAsset: number,
                lessonVideo: number, //视频课程
                expName: string,
                expGuide: string,
                servicePlan: string,
                deviceRequire: string,
                expFeature: string, //虚拟仿真实验课
                teacher: string,
                startTime: {},
                endTime: {}, //直播课

            },

            courseAssetData: [],
        };
    }

    actionRef: any;
    componentWillUnmount() {
        window.onbeforeunload = null;
    }

    componentDidMount() {
        window.onbeforeunload = function (event: any) {
            event.returnValue = "系统不会保存用户数据!";
        };
        APIS.CourseAPI.GetAssetsList({ current: 1, pageSize: 99999 }).then((res) => {
            this.setState({ courseAssetData: res.data });
        });
        var params = new URLSearchParams(this.props.history.location.search);
        var id = null;
        if (params.has('id')) {
            id = parseInt(params.get('id') + '');
            this.setState({ courseId: id });
            APIS.CourseAPI.GetCourseDetail({ id }).then((data) => {
                this.setState({
                    editorData: data,
                    courseTag: [],
                    courseType: data.typeInfo ? data.typeInfo.id : 0,
                    courseMode: data.mode,
                    videoUrl: data.video,
                    imageUrl: data.courseImg,
                    startTime: data.startTime,
                    endTime: data.endTime,
                });
                this.requestGetTeacherData(data.id);
                this.requestGetChapterData();
                //将tags转换为tagIds以供组件使用
                var tagIds: any = [];
                data.tags?.map?.((v: any) => {
                    tagIds = [...tagIds, v.id];
                });
                this.setState({ courseTag: tagIds });
            }).catch(() => {
                message.error("课程信息不存在或者数据错误！");
                this.props.history.replace("teaching/course/list");
            });
        }
    }

    requestGetTeacherData(id: number) {
        APIS.CourseAPI.GetAllCourseMember({ courseId: id }).then((res) => {
            this.setState({ courseTeachers: res });
        });
    }
    requestGetChapterData() {
        APIS.CourseAPI.GetChapterList(this.state.editorData).then((res) => {
            this.setState({ courseChaptersList: res });
            res.map?.((v: any, i: any) => {
                (v.key = i), (v.children = []);
            });
            this.setState({ courseChapters: this.translateDataToTree(res) });
        });
    }
    translateDataToTree(data: any) {
        let parents: Array<any> = data.filter((value: any) => value.parent == 'undefined' || value.parent == null);
        let childrens = data.filter(
            (value: any) => value.parent !== 'undefined' && value.parent != null,
        );
        let translator = (parents: any, childrens: any) => {
            parents.forEach((parent: any) => {
                childrens.forEach((current: any, index: any) => {
                    if (current.parent === parent.id) {
                        let temp = JSON.parse(JSON.stringify(childrens));
                        temp.splice(index, 1);
                        translator([current], temp);
                        typeof parent.children !== 'undefined'
                            ? parent.children.push(current)
                            : (parent.children = [current]);
                    }
                });
                if (parent.children.length === 0) {
                    delete parent.children;
                }
                else {
                    parent.children.sort((a: any, b: any) => a.index - b.index);

                }
            });
        };
        translator(parents, childrens);
        parents.sort((a, b) => a.index - b.index);
        return parents;
    }

    requestGetChapterDetails(data: any) {
        APIS.CourseAPI.GetChapterDetail(data).then((res) => {
            if (res.lessonDetails)
                this.setState({ chapterCourseVisible: true, chapterCourseData: res.lessonDetails });
            else
                this.setState({
                    chapterCourseVisible: true,
                    chapterCourseData: { id: null, chapterId: data.id },
                });
            if (data.lessonType === 3) {
                this.props.history.push({ pathname: 'lesson', search: "id=" + data.id });
            }
        });
    }

    columns: any = [
        {
            title: '章节目录',
            dataIndex: 'chapterName',
            key: 'chapterName',
        },
        {
            title: '类型',
            dataIndex: 'lessonType',
            render: (type: number) => {
                switch (type) {
                    case 1:
                        return '文章课程';
                    case 2:
                        return '视频课程';
                    case 3:
                        return '虚拟仿真实验课';
                    case 4:
                        return '直播课';
                    default:
                        return '空节点';
                }
            },
        },
        // {
        //     title: '排序',
        //     render: (data: any) => {
        //         return <Space>
        //             <a onClick={() => APIS.CourseAPI.MoveChapter({ chapterId: data.id, dir: 1 }).then(() => this.requestGetChapterData())}>
        //                 上升
        //       </a>
        //             <a onClick={() => APIS.CourseAPI.MoveChapter({ chapterId: data.id, dir: -1 }).then(() => this.requestGetChapterData())}>
        //                 下降
        //       </a>
        //         </Space>
        //     },
        // },
        {
            title: '操作',
            render: (data: any) => {
                return (
                    <Space>
                        <a onClick={() => { console.log("跳转到预览界面") }}>
                            预览
                  </a>


                    </Space>
                );
            },
        },
    ];

    private renderCourseInfo() {
        const { RangePicker } = DatePicker;
        return (
            <Collapse.Panel header="课程信息" key="1">
                <Form
                    style={{ marginTop: '20px' }}
                    initialValues={{
                        name: this.state.editorData?.courseName,
                        duration: this.state.editorData?.duration,
                        score: this.state.editorData?.score,
                        state: this.state.editorData?.state,
                        description: this.state.editorData?.description,
                        requireFlag: this.state.editorData?.requireFlag,
                        template: this.state.editorData?.template,
                    }}
                    onFinish={(values) => {
                        if (this.state.courseTag.length < 1 || this.state.courseTag.length > 3) {
                            alert('请选择1~3个标签');
                            return;
                        }
                        // if (this.state.courseType === -1) {
                        //   alert('请选择课程类型');
                        //   return;
                        // }
                        // if (this.state.courseMode === -1) {
                        //     alert('请选择课程形式');
                        //     return;
                        // }
                        // if (!this.state.videoUrl) {
                        //   alert('请上传介绍视频');
                        //   return;
                        // }
                        if (!this.state.imageUrl) {
                            console.log(this.state.imageUrl)
                            alert('请上传课程封面');
                            return;
                        }
                        this.state.editorData
                            ? APIS.CourseAPI.UpdateCourse({
                                id: this.state.editorData.id,
                                courseName: values.name,
                                type: this.state.courseType,
                                tagIds: this.state.courseTag,
                                mode: this.state.courseMode,
                                video: this.state.videoUrl,
                                courseImg: this.state.imageUrl,
                                duration: values.duration,
                                score: values.score,
                                startTime: this.state.startTime,
                                endTime: this.state.endTime,
                                state: values.state ? 1 : 0,
                                description: values.description,
                                requireFlag: values.requireFlag ? 1 : 0,
                                template: values.template ? 1 : 0,
                            }).then(() => alert('修改成功'))
                            : APIS.CourseAPI.CreateNewCourse({
                                courseName: values.name,
                                type: this.state.courseType,
                                tagIds: this.state.courseTag,
                                mode: this.state.courseMode,
                                video: this.state.videoUrl,
                                courseImg: this.state.imageUrl,
                                duration: values.duration,
                                score: values.score,
                                startTime: this.state.startTime,
                                endTime: this.state.endTime,
                                state: values.state ? 1 : 0,
                                description: values.description,
                                requireFlag: values.requireFlag ? 1 : 0,
                                template: values.template ? 1 : 0,
                            }).then((res) => {
                                alert('创建成功');
                                this.props.history.goBack();
                            });
                    }}
                >
                    <Form.Item

                        label="课程名称"
                        name="name"
                        style={{ width: '300px', float: 'left', marginRight: '200px' }}
                        rules={[{ required: true, message: '请输入课程名称' }]}
                    >
                        {
                            this.state.editorData?.courseName
                        }
                    </Form.Item>
                    <Form.Item
                        name="tag"
                        label="课程标签"
                        hasFeedback
                        style={{ width: '300px', float: 'left', marginRight: '200px' }}
                        rules={[{ required: false, message: '请选择课程标签' }]}
                    >
                        <div> {this.state.editorData?.tags.map((item: any, index: number) => {
                            return index === this.state.editorData?.tags.length - 1 ? `${item.tag}` : `${item.tag} 、`;
                        })}</div>

                    </Form.Item>

                    <Form.Item
                        name="mode"
                        label="课程形式"
                        style={{ width: '300px', float: 'left', marginRight: '200px' }}
                        validateStatus={this.state.courseMode === -1 ? 'error' : 'success'}
                    >
                        <SearchAbleSelect
                            searchData={async (key) => {
                                var datas: Array<any> = await APIS.CourseAPI.SearchGetModeList(key);
                                return Promise.resolve(
                                    datas.map((item) => {
                                        return { value: item.id, key: item.modeName };
                                    }),
                                );
                            }}
                            name="mode"
                            placeholder="请选择课程形式"
                            getValue={(value) => this.setState({ courseMode: value.mode })}
                            initialValue={this.state.editorData?.mode}
                            disabled={this.state.editorData ? true : false}
                        />
                    </Form.Item>
                    <div style={{ display: 'flex', justifyContent: 'start', width: '100%' }}>
                        <Form.Item style={{ float: 'left' }}>
                            介绍视频:
                <VideoUploadExamine
                                preVideo={this.state.videoUrl}

                                handleVideoChange={(url: any) => this.setState({ videoUrl: url })}
                            />
                            {/* {console.log(this.state.videoUrl)} */}
                            {/* <Upload
                            accept=".mp4"
                            showUploadList={{showPreviewIcon:true,showRemoveIcon:false}}
                            multiple={false}
                            name="logo"
                           fileList={this.state.videoUrl}
                         disabled={true}
                            /> */}

                        </Form.Item>
                        <Form.Item style={{ float: 'left', marginLeft: '200px' }}>
                            课程封面:
                               <div>
                                <img style={{ width: 100, height: 100 }} src={URLS.SERVER_PICTURE_URL + this.state.editorData?.courseImg}></img>
                            </div>
                        </Form.Item>
                    </div>
                    <br />
                    <br />
                    <Form.Item
                        label="课程学时"
                        name="duration"
                        style={{ width: '300px', float: 'left', marginRight: '200px' }}
                        rules={[{ required: true, message: '请输入课程学时' }]}
                    >
                        {this.state.editorData?.duration}
                    </Form.Item>
                    <Form.Item
                        label="课程学分"
                        name="score"
                        style={{ width: '300px', float: 'left' }}
                        rules={[{ required: true, message: '请输入课程学分' }]}
                    >
                        {this.state.editorData?.score}
                    </Form.Item>
                    <br />
                    <br />
                    <br />
                    <br />
                    <Form.Item
                        label="起止时间"
                        name="time"
                        style={{ width: '300px', float: 'left', marginRight: '200px' }}
                    >
                        {
                            `${moment(this.state.editorData?.startTime).format("YYYY-MM-DD")}~
                           ${moment(this.state.editorData?.endTime).format("YYYY-MM-DD")}`
                        }
                    </Form.Item>
                    {/* <Form.Item
                        label="课程状态"
                        name="state"
                        valuePropName="checked"
                        style={{ float: 'left' }}
                    >
                        <Switch disabled={true} />
                    </Form.Item> */}
                    <br />
                    <br />
                    <br />
                    <br />
                    <Form.Item
                        label="课程简介"
                        name="description"
                        rules={[{ required: true, message: '请输入简介' }]}
                    >

                        <div style={{ width: 500, whiteSpace: "pre-wrap" }}> {this.state.editorData?.description}</div>
                    </Form.Item>
                    <Form.Item
                        label="是否必修"
                        name="requireFlag"
                        valuePropName="checked"
                        style={{ float: 'left', marginRight: '390px' }}
                    >
                        <Switch disabled={true} />
                    </Form.Item>
                    {/* <Form.Item
                        label="是否模板"
                        name="template"
                        valuePropName="checked"
                        style={{ float: 'left' }}
                    >
                        <Switch disabled={true} />
                    </Form.Item> */}
                    <br />
                    {/* <br />
                    <br />
                    <br /> */}
                    {/* <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                {this.state.editorData ? '修改' : '新增'}
                            </Button>
                            <Button type="default" htmlType="button" onClick={() => this.props.history.goBack()}>
                                取消
                </Button>
                        </Space>
                    </Form.Item> */}
                </Form>
            </Collapse.Panel>
        );
    }

    render() {
        const { RangePicker } = DatePicker;

        return (
            <Collapse accordion ghost>
                <div key="0" style={{ display: "flex", justifyContent: "flex-end", marginTop: 10 }}>
                    <Button key="pass" onClick={() => {
                        APIS.CourseAPI.PassCourse({ id: this.state.courseId }).then((resp) => {
                            if (resp.code === 10000) message.success("审核通过");
                            this.props.history.push({ pathname: 'list' })
                        })
                    }} style={{ marginRight: 20 }}>审核通过</Button>
                    <Button
                        key="refuse"
                        onClick={() => {
                            APIS.CourseAPI.RejectCourse({ id: this.state.courseId }).then((resp) => {
                                this.props.history.push({ pathname: 'list' })
                            })
                        }}
                        style={{ marginRight: 20 }}>审核不通过</Button>
                </div>
                {this.renderCourseInfo()}
                <Collapse.Panel header="教学团队" key="2" disabled={!this.state.editorData}>
                    {this.state.courseId > 0 ? <CourseMemberEditor key="5" isShow={false} action={true} courseId={this.state.courseId}></CourseMemberEditor> : null}
                </Collapse.Panel>

                <Collapse.Panel header="课程章节" key="3" disabled={!this.state.editorData}>
                    {/* <Button
                        type="primary"
                        style={{ float: 'right', zIndex: 10000 }}
                        onClick={() => this.setState({ chapterVisible: true })}
                    >
                        新增章节
            </Button> */}
                    <Table key="4" columns={this.columns} dataSource={this.state.courseChapters} />


                </Collapse.Panel>
            </Collapse>
        );
    }
}
